<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              class="vcenter"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              {{ item1.name }}
              <!-- 一级 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级 -->
              <el-col :span="19">
                <el-row
                  class="vcenter"
                  :class="[i2 === 0 ? '' : 'bdtop']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  {{ item2.name }}
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!--  -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditRoleDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoleById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="addRoleDialogVisibleClosed"
    >
      <!-- 内容 -->
      <el-form
        :model="roleform"
        :rules="addroleformRules"
        ref="roleformRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleform.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleform.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--  -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户 -->
    <el-dialog
      title="修改角色信息"
      :visible.sync="editRoleDialogVisible"
      width="30%"
      @close="editRoleDialogClosed"
    >
      <el-form
        :model="editRoleform"
        :rules="editroleformRules"
        ref="editroleformRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleform.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleform.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose"
    >
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addRolesApi,
  delRoleUserApi,
  getRolesDetail,
  editRoles,
  delRolesRoot,
  getAllUserApi,
  getPerApi,
  allotRolesRoot,
} from "@/api/role";
export default {
  name: "RoLes",
  data() {
    return {
      rolelist: [],
      rightslist: [],
      setRightDialogVisible: false,
      addRoleDialogVisible: false,
      editRoleDialogVisible: false,
      roleform: {
        roleName: "",
        roleDesc: "",
      },
      addroleformRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      editroleformRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      editRoleform: {},
      treeProps: {
        label: "authName",
        children: "children",
      },
      defKeys: [],
      roleId: "",
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const res = await getAllUserApi();
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.$message.success("获取角色列表成功");
      this.rolelist = res.data;
      // console.log(this.rolelist);
    },
    addRoleDialogVisibleClosed() {
      this.$refs.roleformRef.resetFields();
    },
    editRoleDialogClosed() {
      this.$refs.editroleformRef.resetFields();
    },
    addRoleUser() {
      this.$refs.roleformRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return;
        const res = await addRolesApi(this.roleform);
        // console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
        this.addRoleDialogVisible = false;
        this.getRolesList();
      });
    },
    // 删除用户,点击删除按钮时，将该用户的 id 传过来
    async deleteRoleById(id) {
      // 弹框提示是否删除
      const res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err); // 捕获异常
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (res !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // 如果确认了删除，则发起 axios 删除请求
      const deleteres = await delRoleUserApi(id);
      console.log(deleteres);
      if (deleteres.meta.status !== 200) {
        if (deleteres.meta.status === 400)
          return this.$message.error("不允许删除admin账户！");
        return this.$message.error("删除失败");
      }
      this.getRolesList();
      this.$message.success("删除成功");
    },
    async showEditRoleDialog(id) {
      // console.log(id);
      const res = await getRolesDetail(id);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户信息失败");
      }
      this.editRoleform = res.data;
      console.log(this.editRoleform);
      this.editRoleDialogVisible = true;
    },
    editRoleUserInfo() {
      this.$refs.editroleformRef.validate(async (valid) => {
        if (!valid) return;
        // const { mobile, email, id } = this.editform;
        const res = await editRoles(this.editRoleform.roleId, {
          roleName: this.editRoleform.roleName,
          roleDesc: this.editRoleform.roleDesc,
        });
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("更新用户信息失败");
        }

        this.editRoleDialogVisible = false;
        this.getRolesList();
        this.$message.success("更新用户信息成功");
      });
    },
    async removeRightById(row, perid) {
      // 弹框提示是否删除
      const res = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err); // 捕获异常
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (res !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // console.log("确认了删除");
      // 如果确认了删除，则发起 axios 删除请求
      const deleteuse = await delRolesRoot(row.id, perid);
      console.log(deleteuse);
      if (deleteuse.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.getRolesList();
      // role.children = res.data;
      this.$message.success("删除成功");
    },
    async showSetRightDialog(role) {
      this.roleId = role.id;
      const res = await getPerApi();

      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.rightslist = res.data;
      // console.log(this.rightslist);
      this.getLeafKeys(role, this.defKeys);
      this.setRightDialogVisible = true;
    },
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    setRightDialogClose() {
      this.keys = [];
    },
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      console.log(keys);

      const idStr = keys.join(",");

      const res = await allotRolesRoot(this.roleId, { rids: idStr });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败");
      }
      this.$message.success("分配权限成功");
      this.getRolesList();
      this.setRightDialogVisible = false;
    },
  },
};
</script>

<style scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-table__cell.el-table__expanded-cell {
  padding: 20px 50px;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
